const { src, dest, task, series, parallel, watch } = require("gulp");
const imgmin = require("gulp-imagemin");
const useref = require("gulp-useref");
const del = require("del");
const browserSync = require("browser-sync");
const swig = require("gulp-swig");
const babel = require("gulp-babel");

const paths = {
  base: "src",
  html: "src/*.html",
  script: "src/script/**.js",
  style: "src/style/**.css",
  img: ["src/img/*.{png,jp{,e}g}"],
  dist: "dist",
};

const page = {
  index: { title: "代码二" },
};

const clean = (done) => del(`${paths.dist}`, done);

const script = () =>
  src(paths.script, { base: paths.base }).pipe(babel()).pipe(dest(paths.dist));

const style = () =>
  src(paths.style, { base: paths.base }).pipe(dest(paths.dist));

const html = () =>
  src(paths.html, { base: paths.base })
    .pipe(swig({ defaults: { cache: false }, data: page }))
    .pipe(dest(paths.dist));

const pack = () =>
  src(`${paths.dist}/*.html`)
    .pipe(useref({ searchPath: "dist" }))
    .pipe(dest(paths.dist));

const image = () =>
  src(paths.img, { base: paths.base }).pipe(imgmin()).pipe(dest(paths.dist));

const serve = () => {
  watch(paths.html, html);
  watch(paths.script, script);
  watch(paths.style, style);
  watch(paths.img, image);

  browserSync({
    port: 3080,
    watch: true,
    server: {
      baseDir: ["dist", "."],
      index: "index.html",
    },
  });
};

const copy = parallel(style, image, script, html);
const build = series(clean, copy, pack);
const dev = series(copy, serve);

exports.default = build;
exports.dev = dev;
